import axios from 'axios'
import QS from 'qs'

export const BASE_URL = process.env.API_BASE_URL;
let {hostname} = window.location;
let baseUrl = '';
if (hostname.indexOf('yixiatong') > -1 || hostname.indexOf('localhost') > -1 || location.search.indexOf('test=1') > -1) {
    baseUrl = BASE_URL['yixiatong'];
} else {
    baseUrl = BASE_URL['yixia'];
}

// 创建axios实例
const service = axios.create({
    baseURL: baseUrl, // api的base_url
    timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
    if (config.method === 'post') {
        if (localStorage.getItem('token')) {
            config.data || (config.data = {})
            config.data._csrf = localStorage.getItem('token')
        }
        config.data = QS.stringify(config.data)
    }
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
    return config
}, error => {
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.data && res.data.token || res.token) {
            window.localStorage.token = res.token || res.data.token;
        }
        return res
    },
    error => {
        return Promise.reject(error)
    }
)

export default service
